import type { RouteRecordRaw } from "vue-router";
import { componentMapping } from "@/router/route";

interface MenuItem {
  children: any;
  menu_id: number;
  path: string;
  name: string;
  component: string | null;
  redirect: string | null;
  parent_id: number;
  order_num: number;
  hidden: boolean | number;
  meta_title?: string;
  meta_icon?: string;
  always_show?: boolean | number;
  affix?: boolean | number;
}

// 将数据库数据转换为树形结构
export function buildMenuTree(menuItems: MenuItem[]): MenuItem[] {
  // console.log("XZC", menuItems);

  // 收集所有存在的menu_id
  const existingIds = new Set(menuItems.map((item) => item.menu_id));

  // 过滤无效子项
  const validItems = menuItems.filter(
    (item) =>
      item.parent_id === 0 ||
      item.parent_id === 1 ||
      existingIds.has(item.parent_id)
  );

  const itemMap: Record<number, MenuItem> = {};
  const tree: MenuItem[] = [];

  // 创建哈希表
  validItems.forEach((item) => {
    itemMap[item.menu_id] = { ...item };
  });

  // 构建树形结构
  validItems.forEach((item) => {
    const parent = itemMap[item.parent_id];
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(itemMap[item.menu_id]);
    } else {
      tree.push(itemMap[item.menu_id]);
    }
  });

  // 排序处理
  const sortByOrder = (a: MenuItem, b: MenuItem) => a.order_num - b.order_num;
  tree.sort(sortByOrder);
  tree.forEach((item) => item.children?.sort(sortByOrder));

  // console.log("ASDASD", tree);

  return tree;
}

// 生成Vue路由配置
export function generateRoutes(menuTree: MenuItem[]): RouteRecordRaw[] {
  return menuTree.map((menu) => convertToRoute(menu));
}

function convertToRoute(menu: MenuItem): RouteRecordRaw {
  const route: RouteRecordRaw = {
    path: menu.path,
    name: menu.name,
    component: menu.component ? componentMapping[menu.component] : undefined,
    redirect: menu.redirect || undefined,
    meta: {
      title: menu.meta_title,
      icon: menu.meta_icon,
      affix: Boolean(menu.affix),
      hidden: Boolean(menu.hidden),
      alwaysShow: Boolean(menu.always_show),
    },
    children: menu.children
      ? menu.children.map((child: MenuItem) => convertToRoute(child))
      : [],
  };

  // 处理嵌套路由路径
  if (menu.parent_id !== 0 && !menu.path.startsWith("/")) {
    route.path = menu.path;
  }

  return route;
}

// 生成侧边栏菜单结构
export function generateSidebar(menuTree: MenuItem[]): any[] {
  return menuTree
    .filter((item) => !item.hidden)
    .map((menu) => convertToSidebarItem(menu));
}

function convertToSidebarItem(menu: MenuItem): any {
  return {
    path: menu.path,
    meta: {
      title: menu.meta_title,
      icon: menu.meta_icon,
    },
    children: menu.children ? generateSidebar(menu.children) : undefined,
    alwaysShow: Boolean(menu.always_show),
  };
}

// 定义树节点类型
export interface TreeNode {
  value: string
  label: string
  children: TreeNode[]
}

/**
 * 将菜单列表转换为树形结构
 * @param menuItems 原始菜单数据
 * @returns 格式化后的树形数据
 */
export function convertToTreeData(menuItems: MenuItem[]): TreeNode[] {
  // 创建哈希映射和结果集
  const nodeMap = new Map<number, TreeNode>()
  const result: TreeNode[] = []

  // 第一次遍历：创建所有节点
  menuItems.forEach(item => {
    const node: TreeNode = {
      value: item.menu_id.toString(),
      label: item.meta_title || item.name,
      children: []
    }
    nodeMap.set(item.menu_id, node)
  })

  // 第二次遍历：构建树结构
  menuItems.forEach(item => {
    const currentNode = nodeMap.get(item.menu_id)!
    
    if (item.parent_id === 0) {
      // 根节点处理
      result.push(currentNode)
    } else {
      // 子节点处理
      const parentNode = nodeMap.get(item.parent_id)
      parentNode?.children.push(currentNode)
    }
  })

  // 递归排序函数
  const sortChildren = (nodes: TreeNode[]) => {
    nodes.forEach(node => {
      node.children.sort((a, b) => {
        const aItem = menuItems.find(m => m.menu_id === Number(a.value))
        const bItem = menuItems.find(m => m.menu_id === Number(b.value))
        return (aItem?.order_num || 0) - (bItem?.order_num || 0)
      })
      sortChildren(node.children)
    })
  }

  // 执行排序
  sortChildren(result)

  return result
}
